package tr.helper.controller.wine;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.net.HttpCookie;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.util.Pair;
import org.apache.commons.lang3.StringUtils;
import tr.helper.CommonUtil;
import tr.helper.UserHolder;
import tr.helper.controller.Context;
import tr.helper.controller.SecurityController;
import tr.helper.controller.home.HomeMain;
import tr.helper.controller.user.UserAddController;
import tr.helper.repository.table.User;
import tr.helper.view.WineUserItem;

/**
 * tr-service
 *
 * @author MrYe
 * @date 2022-01-21 14:28
 */
public class WineController extends SecurityController {

    @FXML
    private TableView<WineUserItem> selectUsers;

    @FXML
    private TextField txtProductId;

    @FXML
    private TextField txtSpeed;

    @FXML
    private WebView wvProduct;

    @FXML
    private Button btnStart;

    private ObservableList items = FXCollections.observableArrayList();

    @FXML
    private ListView<String> listLog;

    @FXML
    private CheckBox useHighSpeed;

    public Stage userStage = null;

    private Service<Double> service;

    private boolean stop = true;

    public static Executor exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

    public void putUsers(ObservableList<WineUserItem> users) {
        selectUsers.getColumns().addAll(CommonUtil.getTableCols(WineUserItem.class));
        selectUsers.getItems().clear();
        selectUsers.getItems().addAll(users);
        selectUsers.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    }

    @FXML
    public void clearLog() {
        Platform.runLater(() -> {
            items.clear();
            listLog.getItems().clear();
        });
    }

    public void addLog(String msg, Object... args) {
        Platform.runLater(() -> {
            if (items.size() > 300) {
                items.clear();
                listLog.getItems().clear();
            }
            items.add(String.format(msg, args));
            listLog.setItems(items);
        });
    }

    @FXML
    public void doSelect() throws Exception {
        AnchorPane pane = FXMLLoader.load(CommonUtil.getFxmlResource("user/UserListForm.fxml"));
        if (null != userStage) {
            userStage.close();
            userStage = null;
        }
        userStage = new Stage();
        userStage.setScene(new Scene(pane));
        userStage.setTitle("辅助中心 欢迎你:" + UserHolder.getInstance().getUser().getUsername());
        userStage.show();
    }

    @FXML
    public void doAutoOrder() {
        if (CollectionUtil.isEmpty(selectUsers.getItems())) {
            CommonUtil.alert(HomeMain.getInstance(), "请先选择要查看的用户");
            return;
        }

        btnStart.setDisable(true);
        service = new Service<Double>() {
            @Override
            protected Task<Double> createTask() {
                return new Task<Double>() {
                    @Override
                    protected Double call() {
                        doStart(true);
                        btnStart.setDisable(false);
                        return null;
                    }
                };
            }
        };
        service.restart();
    }

    @FXML
    public void doLogin() {
        if (CollectionUtil.isEmpty(selectUsers.getItems())) {
            CommonUtil.alert(HomeMain.getInstance(), "请先选择要查看的用户");
            return;
        }
        List<WineUserItem> newUsers = FXCollections.observableArrayList();
        List<WineUserItem> users = selectUsers.getItems();
        try {
            for (WineUserItem user : users) {
                addLog("开始登录账号:%s", user.getUsername());
                HttpResponse loginResponse = jiuxianService.login(user.getUsername(), user.getPassword());
                JSONObject loginJson = JSON.parseObject(loginResponse.body());
                if (loginJson.getIntValue("success") != 1) {
                    addLog("账号:%s 登录返回:%s", user.getUsername(), loginJson.getString("errMsg"));
                    return;
                }
                JSONObject result = (JSONObject) loginJson.get("result");
                JSONObject userInfo = (JSONObject) result.get("userInfo");
                final String token = userInfo.getString("token");

                StringBuilder cookieBuilder = new StringBuilder();
                for (HttpCookie cookie : loginResponse.getCookies()) {
                    cookieBuilder.append(cookie.toString()).append(";");
                }
                String cookies = cookieBuilder.toString();
                User updUser = new User();
                updUser.setId(user.getId());
                updUser.setTokenTime(new Date());
                updUser.setCookie(cookies);
                updUser.setToken(token);
                userDao.updateByPrimaryKey(updUser, user.getId());

                user.setMobile(userInfo.getString("mobile"));
                user.setToken(token);
                user.setTokenTime(new Date());

                newUsers.add(user);
                addLog("账号:%s 登录成功 更新令牌:%s", user.getUsername(), token);
            }

            selectUsers.getItems().clear();
            selectUsers.getItems().addAll(newUsers);
        } catch (Exception e) {
            addLog("登录异常:%s", e.getMessage());
        }
    }

    private void doStart(boolean useThread) {
        stop = false;
        List<WineUserItem> users = selectUsers.getItems();
        if (useThread) {
            eachCreate(users);
        } else {
            for (WineUserItem user : users) {
                createOrder(user);
            }
        }
    }

    @FXML
    public void doStop() {
        stop = true;
        boolean cancel = service.cancel();
        addLog("任务取消:%s", cancel);
        btnStart.setDisable(false);
    }

    private void eachCreate(List<WineUserItem> users) {
        for (WineUserItem user : users) {
            if (useHighSpeed.isSelected()) {
                exec.execute(() -> createOrder(user));
            } else {
                createOrder(user);
            }
        }
        if (!stop) {
            CommonUtil.sleep(Integer.parseInt(txtSpeed.getText()));
            eachCreate(users);
        }
    }

    private void createOrder(WineUserItem user) {
        if (StringUtils.isBlank(user.getToken())) {
            addLog("账号:%s 未登录", user.getUsername());
            return;
        }
        addLog("账号:%s 开始下单", user.getUsername());
        try {
            // 查询收获地址
            HttpResponse addressResponse = jiuxianService.getAddress(user.getToken());
            JSONObject addressJson = JSON.parseObject(addressResponse.body());
            if (addressJson.getIntValue("success") != 1) {
                addLog("账号:%s 下单失败 返回:%s", user.getUsername(), addressJson.getString("errMsg"));
                return;
            }
            JSONArray addressList = (JSONArray) ((JSONObject) addressJson.get("result")).get("addrList");
            JSONObject addressObj = new JSONObject();
            if (addressList.size() > 0) {
                addressObj = ((JSONObject) addressList.get(0));
            }
            addLog("账号:%s 获取下单地址:%s", user.getUsername(), addressObj.toJSONString());

            HttpResponse makeOrder;
            if ("626626".equals(txtProductId.getText())) {
                makeOrder = jiuxianService.makeSpecialOrder("apiVersion=1.0&appKey=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&appVersion=9.0.10&areaId=" + addressObj.getLong("districtId")
                    + "&channelCode=0,1&cityName=上海市&cpsId=appstore&deviceIdentify=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&deviceType=IPHONE&deviceTypeExtra=0&equipmentType=iPhone&lati=31.3627880859375&longi=121.5511895073785&netEnv=unkown&orderAddInfo={\"reservationToken\":\"\",\"toUseCashBack\":\"0\",\"orderDelivery\":[],\"couponId\":\"\",\"isBuyImmediately\":\"1\",\"payType\":\"1\",\"toUseAllowance\":\"0\",\"coldNum\":0,\"toUseCoupon\":\"0\",\"invType\":\"0\",\"invTitle\":\"\",\"productId\":\"626626\",\"invMobile\":\"18521057139\",\"stockoutGifts\":\"\",\"isGiftOrder\":\"0\",\"isReservation\":1,\"buyNum\":\"1\",\"invContent\":\"\",\"deliveryId\":\"16\",\"invKind\":\"0\"}&pushToken=&screenReslolution=414.00x896.00&supportWebp=1&sysVersion=13.6.1&token="
                    + user.getToken());
            } else {
                // 添加到购物车
                String query =
                    "apiVersion=1.0&appKey=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&appVersion=9.0.10&areaId=" + addressObj.getLong("districtId")
                        + "&channelCode=0,1&cityName=上海市&cpsId=appstore&deviceIdentify=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&deviceType=IPHONE&deviceTypeExtra=0&equipmentType=iPhone&lati=31.31619411892361&longi=121.4094590928819&netEnv=unkown&orderSetInfo={\"toUseCoupon\":\"-1\",\"isGiftOrder\":\"-1\",\"productInfo\":{\"normalList\":[{\"productId\":\""
                        + txtProductId.getText()
                        + "\",\"buyNum\":\"1\"}]},\"isXinKe\":0,\"isBuyImmediately\":\"1\",\"isPresell\":0,\"invType\":\"0\",\"payType\":\"0\",\"invKind\":\"-1\",\"stockoutGifts\":\"\",\"toUseAllowance\":\"-1\",\"toUseCashBack\":\"1\",\"coldNum\":0,\"isReservation\":0}&pushToken=&screenReslolution=414.00x896.00&supportWebp=1&sysVersion=13.6.1&token="
                        + user.getToken();

                HttpResponse addResponse = jiuxianService.addCart(query);
                addLog("账号:%s 添加购物车返回状态码%s", user.getUsername(), addResponse.getStatus());
                if (addResponse.getStatus() != 200) {
                    return;
                }
                JSONObject addJson = JSON.parseObject(addResponse.body());
                if (addJson.getIntValue("success") != 1) {
                    addLog("账号:%s 添加购物车失败 返回:%s", user.getUsername(), addJson.getString("errMsg"));
                    return;
                }

                makeOrder = jiuxianService.makeOrder("apiVersion=1.0&appKey=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&appVersion=9.0.10&areaId=" + addressObj.getLong("districtId")
                    + "&channelCode=0,1&cityName=上海市&cpsId=appstore&deviceIdentify=BFE41A56-B351-4541-89E8-E0BA0D6BB29D&deviceType=IPHONE&deviceTypeExtra=0&equipmentType=iPhone&lati=31.31619411892361&longi=121.4094590928819&netEnv=unkown&orderAddInfo={\"toUseCoupon\":\"0\",\"invTitle\":\"\",\"couponId\":\"\",\"isGiftOrder\":\"0\",\"invMobile\":\""
                    + user.getMobile() + "\",\"isBuyImmediately\":\"1\",\"addressId\":\""
                    + addressObj.getLong("addrId")
                    + "\",\"toUseCashBack\":\"0\",\"payType\":\"1\",\"invKind\":\"0\",\"invType\":\"0\",\"toUseAllowance\":\"0\",\"invContent\":\"\",\"deliveryId\":\"16\",\"userLeaveMessage\":\"test\",\"stockoutGifts\":\"\",\"coldNum\":0,\"orderDelivery\":[]}&pushToken=&screenReslolution=414.00x896.00&supportWebp=1&sysVersion=13.6.1&token="
                    + user.getToken());
            }

            JSONObject orderJson = JSON.parseObject(makeOrder.body());
            if (orderJson.getIntValue("success") != 1) {
                addLog("账号:%s 下单失败 返回:%s", user.getUsername(), orderJson.getString("errMsg"));
                return;
            }
            JSONObject orderResult = (JSONObject) orderJson.get("result");

            // 发送邮件
            CommonUtil.sendNotice("账号:%s 商品编号:%s %s 订单编号:%s 价格:%s", user.getUsername(), txtProductId.getText(), orderResult.getString("backInfor"), orderResult.getString("orderSn"),
                orderResult.getString("payPrice"));
            addLog("账号:%s 下单成功", user.getUsername());
        } catch (Exception e) {
            addLog("账号:%s 下单异常 %s", user.getUsername(), e.getMessage());
        }
    }

    @FXML
    public void doAdd() throws Exception {
        AnchorPane userPane = FXMLLoader.load(CommonUtil.getFxmlResource("user/UserAddForm.fxml"));
        if (null != userStage) {
            userStage.close();
            userStage = null;
        }
        userStage = new Stage();
        userStage.setScene(new Scene(userPane));
        userStage.setTitle("选择酒仙用户");
        userStage.show();

        UserAddController userAddController = (UserAddController) Context.controllers.get(UserAddController.class.getSimpleName());
        userAddController.boxChoice.setValue(new Pair<>("", 0L));
    }

    @FXML
    public void doLoad() {
        WebEngine e = wvProduct.getEngine();
        // load a website
        e.load("https://m.jiuxian.com/m_v1/goods/view/" + txtProductId.getText());
    }

    @FXML
    public void doOrder() {
        if (CollectionUtil.isEmpty(selectUsers.getItems())) {
            CommonUtil.alert(null, "请先选择要下单的用户");
            return;
        }
        clearLog();
        doStart(false);
    }

    @Override
    public void init(URL location, ResourceBundle resources) {
        addLog("当前高速默认线程数:%s", Runtime.getRuntime().availableProcessors() * 2);
    }

}
